<template>
  <div>
    <!-- 面包屑 -->
    <!-- <app-bread>{{ $route.meta.title }}</app-bread> -->

    <!-- 查询功能 -->
    <el-form :inline="true" :model="searchForm" ref="retfrom" class="search">
      <!-- ref 类似于id的作用 -->
      <el-form-item prop="name">
        <!-- prop:表单域 model 字段，在使用 validate、resetFields 方法的情况下，该属性是必填的 -->
        <el-input
          v-model="searchForm.name"
          placeholder="用户名"
          style="width:160px"
        ></el-input>
      </el-form-item>
      <el-form-item prop="sex">
        <el-select
          v-model="searchForm.sex"
          placeholder="性别"
          style="width:80px"
        >
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchData(searchForm)"
          >查询</el-button
        >
        <el-button type="primary" @click="reset('retfrom')">重置</el-button>
        <el-button type="success" @click="dialogFormVisible = true"
          >新增</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 用户列表数据 border加边框，stripe：斑马纹 -->
    <template>
      <el-table :data="tableData" border style="width: 100%" stripe>
        <el-table-column prop="name" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="sex" label="性别" width="100"> </el-table-column>
        <el-table-column prop="phone" label="手机号码" width="180">
        </el-table-column>
        <el-table-column prop="birthday" label="生日日期" width="180">
        </el-table-column>
        <el-table-column prop="address" label="地址"> </el-table-column>
        <el-table-column label="头像" width="80">
          <template slot-scope="scope">
            <img :src="scope.row.pic" style="width:60px;height:60px;" alt="" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="操作" width="150">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="success"
              @click="editUser(scope.row._id)"
              >编辑</el-button
            >
            <el-button size="mini" type="danger" @click="del(scope.row._id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top:20px;float:right;"
      >
      </el-pagination>

      <!-- 新增和编辑 -->
      <el-dialog
        :title="isAdd ? '添加用户' : '编辑用户'"
        :visible.sync="dialogFormVisible"
        width="600px"
      >
        <el-form :model="form" ref="form" label-position="right" :rules="rules">
          <el-form-item label="姓名" :label-width="iw" prop="name">
            <el-input
              v-model="form.name"
              autocomplete="off"
              style="width:200px"
              placeholder="请输入用户名"
            ></el-input>
          </el-form-item>
          <el-form-item label="性别" label-width="100px" prop="sex">
            <el-select v-model="form.sex" placeholder="性别" style="width:80px">
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="手机" :label-width="iw" prop="phone">
            <el-input
              v-model.trim="form.phone"
              autocomplete="off"
              style="width:200px"
              placeholder="请输入手机号码"
            ></el-input>
          </el-form-item>
          <el-form-item label="出生日期" :label-width="iw" prop="birthday">
            <el-date-picker
              v-model="form.birthday"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>

          <el-form-item label="地址" :label-width="iw" prop="address">
            <el-input
              v-model="form.address"
              autocomplete="off"
              style="width:200px;resize:none;"
              placeholder="请输入地址"
              type="textarea"
            ></el-input>
          </el-form-item>
          <el-form-item label="上传图片" :label-width="iw" prop="pic">
            <el-upload
              class="upload-demo"
              ref="upload"
              action="/dev-api/user/adduser"
              :http-request="httpRequest"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-change="onChange"
              :before-remove="beforeRemove"
              multiple
              :limit="3"
              :on-exceed="handleExceed"
              :file-list="fileList"
              name="photos"
              :auto-upload="false"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <!-- <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div> -->
            </el-upload></el-form-item
          >
        </el-form>

        <div slot="footer" class="dialog-footer">
          <!-- <template slot-scope="scope"> -->
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="isAdd ? add() : edit(form._id)"
            >确 定</el-button
          >
          <!-- </template> -->
        </div>
      </el-dialog>
    </template>
  </div>
</template>


<script>
import userApi from "../../api/userApi";

export default {
  data() {
    var validatePsw = (rule, value, callback) => {
      /*
        value:该表单的value值
        callback：回调函数，返回提示信息
      */
      let reg = /1[3-9]\d{9}/;
      if (reg.test(value) && value.length == 11) {
        callback(); //类似于next的意思
      } else {
        callback(new Error("请输入正确的手机号码"));
      }
    };
    return {
      searchForm: {
        name: "",
        sex: ""
      },
      tableData: [],
      page: 1, //当前是第几页
      pageSize: 10,
      total: 0,
      dialogFormVisible: false, //弹窗的开关
      rules: {
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" } //姓名不能为空
        ],
        phone: [
          { required: true, message: "手机号码不能为空", trigger: "blur" }, //用户名不能为空
          { validator: validatePsw, trigger: "blur" } //验证手机号码是否符合要求
        ]
      }, //表单验证的规则
      form: {
        //新增用户数据
        name: "",
        sex: "",
        phone: "",
        birthday: "",
        address: ""
        // pic: ""
      },
      // ruleForm: {
      //   name: "",
      //   sex: "",
      //   phone: "",
      //   birthday: "",
      //   address: ""
      // },
      iw: "100px",
      isAdd: true, //对话框类别初始值  true:添加用户 false为编辑用户
      fileList: [
        //存储图片的地方：已上传图片
        // {
        //   name: "food.jpeg",
        //   url:
        //     "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100"
        // },
        // {
        //   name: "food2.jpeg",
        //   url:
        //     "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100"
        // }
      ]
    };
  },

  components: {},

  methods: {
    //功能：查询用户列表
    fetchData() {
      // console.log(query, 777);
      if (this.searchForm.name != "" && this.searchForm.sex != "") {
        userApi.getlist(this.page, this.pageSize, this.searchForm).then(res => {
          console.log(res.data, 123);
          this.total = res.data.total;
          this.tableData = res.data.datalist;
        });
      } else {
        // this.$message({
        //   type: "error",
        //   message: "查询失败！请精确输入查询信息"
        // });
        userApi.getlist(this.page, this.pageSize).then(res => {
          console.log(res.data, 123);
          this.total = res.data.total;
          this.tableData = res.data.datalist;
        });
      }
    },

    //功能：重置查询表单
    reset(form) {
      // console.log(form, "resetfrom");
      this.$refs[form].resetFields();
      this.fetchData();
    },

    //功能：点击打开编辑用户的窗口
    editUser(id) {
      // console.log(id, 776);
      this.dialogFormVisible = true; //点击打开弹窗
      this.isAdd = false; //编辑弹窗设置为false
      this.fileList = []; //每次打开编辑窗口先清空里面的图片
      userApi.getuser(id).then(res => {
        console.log(res.data.datalist, 8888);
        this.form = res.data.datalist[0];

        //获取图片pic
        let obj = {
          name: this.form.fileNames,
          url: this.form.pic
        };
        this.fileList.push(obj); //设置已上传文件的回显
      });
    },

    //功能：编辑用户(点击确认按钮，修改用户信息)
    edit(id) {
      // console.log(this.form._id, 666);
      this.$refs.upload.submit(); //提交图片
      //正则校验通过：运行上传数据添加新用户
      let form = new FormData();
      form.append("name", this.form.name);
      form.append("sex", this.form.sex);
      form.append("phone", this.form.phone);
      form.append("birthday", this.form.birthday);
      form.append("address", this.form.address);
      // form.append("_id", this.form._id);
      // form.append("form", JSON.stringify(this.form));

      // console.log(this.fileList);
      this.fileList.forEach(file => {
        //接口那边：req.files
        form.append("avatar", file.raw); //此处一定是append file.raw 上传文件只需维护fileList file.raw.name要加上
        form.append("fileNames", file.name);
      });

      //把数据以form-data的形式发送给后端
      userApi.editUser(form, id).then(res => {
        console.log(id);
        console.log(res.data, 99999);
        if (res.data.flag) {
          //修改成功
          this.$message({
            message: "修改成功",
            type: "success"
          });

          //关闭弹窗并刷新页面
          this.dialogFormVisible = false;
          this.fetchData();
        } else {
          //修改失败
          this.$message({
            message: "修改失败",
            type: "error"
          });
        }
      });
    },

    //功能：删除用户
    del(id) {
      console.log(id, 999);
      this.$confirm("您确定要删除该用户吗？", "删除提示", {
        confirmButtonText: "确实",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          //确定要删除
          userApi.delUser(id).then(res => {
            if (res.data.flag) {
              //删除成功
              this.$message({
                type: "success",
                message: "删除成功！"
              });

              //刷新页面
              this.fetchData();
            } else {
              this.$message({
                type: "error",
                message: "删除失败！"
              });
            }
          });
        })
        .catch(() => {
          //取消删除
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    //功能：监听一页多少条已经改变
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pageSize = val; //每页多少页
      this.page = 1; //如果切换每页多少条，回到第一页开始看
      this.fetchData();
    },

    //功能：跳转到第n页
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.page = val;
      this.fetchData();
    },

    //功能：添加新用户：确定的时候，把内容提交给后台
    add() {
      this.$refs.form.validate(async res => {
        console.log(res);
        if (res) {
          //手动提交图片的关键
          this.$refs.upload.submit(); //提交图片
          //正则校验通过：运行上传数据添加新用户
          let form = new FormData(); //ES5 新增方法
          form.append("name", this.form.name);
          form.append("sex", this.form.sex);
          form.append("phone", this.form.phone);
          form.append("birthday", this.form.birthday);
          form.append("address", this.form.address);
          // form.append("pic", this.form.pic);

          console.log(this.fileList);
          this.fileList.forEach(file => {
            console.log(file.raw, 999);
            form.append("avatar", file.raw); //此处一定是append file.raw 上传文件只需维护fileList file.raw.name要加上
            form.append("fileNames", file.name);
          });

          // console.log(form);
          try {
            let p = await userApi.addUser(form);
            console.log(p.data);
            if (p.data.flag) {
              //提交成功
              this.$message({
                message: "添加成功",
                type: "success"
              });
              this.dialogFormVisible = false; //关闭弹窗
            } else {
              this.$message({
                message: "添加失败",
                type: "error"
              });
            }
          } catch (err) {
            console.log(err);
          }
        } else {
          //校验没通过：不能提交
          this.$message({
            message: "注意书写条件哦",
            type: "error"
          });
        }
      });
    },

    //功能：文件上传（上传头像）
    httpRequest(file) {
      //console.log(file,111);
    },
    onChange(file, fileList) {
      this.fileList = fileList;
      // this.file = file.raw;
      // this.fileName = file.name;
      console.log(fileList);
      console.log(this.fileList);
    },

    //功能：删除已上传图片
    async handleRemove(file, fileList) {
      //删除文件
      console.log(file, fileList);
      console.log(this.form._id);
      // let url = file.url;
      try {
        let data = await userApi.delUserimg(this.form._id);
        if (data.data.flag) {
          //删除陈宫弹出提示信息
          this.fetchData();
          this.$message({
            message: "删除成功",
            type: "sucess"
          });
        } else {
          this.$message({
            message: "删除失败",
            type: "warning"
          });
        }
      } catch (err) {
        this.$message({
          message: "服务器异常，稍后再试",
          type: "error"
        });
      }
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },

    //功能：删除图片前提示
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },

    //功能：

    //功能：新增新用户
    adduser() {
      this.isAdd = true; //添加用户,开关设置为true
      this.dialogFormVisible = true;
      // this.ruleForm = {}; //每次打开弹窗都清空表单：只能清空普通表单内容
      this.fileList = []; //清空图片列表
      this.$nextTick(() => {
        //   //this.$nextTick()它是一个异步事件，当渲染结束之后，它的回调函数才会被执行
        //   //弹出窗口打开之后，需要加载Dom就需要话费一点时间，我们就应该等待它加载完dom之后，再进行调用resetFields方法，重置表单和清楚样式
        this.$refs["form"].resetFields();
      });
    }
  },

  created() {
    console.log("我进来了");
    this.fetchData();
  }
};
</script>

<style scoped>
.search {
  margin-top: 20px;
}
</style>